
package com.example.teacher.http

import android.util.Log
import okhttp3.*
import java.io.IOException
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit

/**
 *@Created by 覃德玮 on 2021/9/6 11:58
 *@Email: chadewik@foxmail.com
 *@Description:
 */
object OkHttp {

    var data: String? =null

    val client=OkHttpClient.Builder()
        .connectTimeout(15,TimeUnit.SECONDS)
        .readTimeout(10,TimeUnit.SECONDS)
        .writeTimeout(10,TimeUnit.SECONDS)
        .build()

    fun get(url:String):String?{

        val latch=CountDownLatch(1)

        Thread(Runnable {
            val request = Request.Builder()
                .url(url)
                .build()

            val call = client.newCall(request)
            val respone = call.execute()
            data= respone.body().string()
            Log.d("body1", ""+data)
            latch.countDown()
        }).start()
        latch.await()
        Log.d("body2", ""+data)
        return data
    }

    fun getSync(url: String?):String?{

        val latch=CountDownLatch(1)

        val request = Request.Builder()
            .url(url)
            .build()

        val call = client.newCall(request)
        call.enqueue(object : Callback {
            override fun onFailure(call: Call?, e: IOException?) {
                Log.d("exception", "error:"+e.toString())
            }

            override fun onResponse(call: Call?, response: Response?) {
                if (response != null) {
                    data = response.body().string()
                    Log.d("body", "" + data)
                    latch.countDown()
                }
            }

        })
        latch.await()
        Log.d("data2", "" + data)
        return data
    }

    fun post(url:String):String?{
        val body=FormBody.Builder().build()
        val request=Request.Builder().url(url)
            .post(body)
            .build()
        val call= client.newCall(request)
        Thread(Runnable {
            val respone = call.execute()
            data=respone.body().string()
            Log.d("post", "post: "+respone.body().string())
        }).start()
        return data
    }
}